package com.diao.myhub.config;

import com.alibaba.fastjson.JSON;
import com.diao.myhub.exception.ICustomizeError;
import com.diao.myhub.model.vo.BaseResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
@RequiredArgsConstructor
public class CommonResBodyAdvice implements ResponseBodyAdvice<Object> {
    private final ObjectMapper mapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getContainingClass().isAnnotationPresent(RestController.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (BaseResponse.class.isAssignableFrom(body.getClass())) {
            return body;
        }
        if (body instanceof ICustomizeError customizeError) {
            return BaseResponse.error(customizeError);
        }
        if (body instanceof String sBody){
            try {
                // 重新设置响应头保证，响应类型
                ServletServerHttpResponse resp = (ServletServerHttpResponse) response;
                resp.getHeaders().set("Content-Type", "application/json;charset=UTF-8");
                return mapper.writeValueAsString(BaseResponse.ok(sBody));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        return BaseResponse.ok(body);
    }
}
